package com.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.media.config.RabbitMqConfig;
import com.media.feignclient.MessageClient;
import com.media.mapper.PublishMapper;
import com.media.mapper.PublishRecodeMapper;
import com.media.model.Media;
import com.media.model.Publish;
import com.base.model.R;
import com.media.model.User;
import com.media.service.MediaService;
import com.media.service.PublishRecodeService;
import com.media.service.PublishService;
import com.media.utils.SecurityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Lenovo
 * @Description: TODO
 * @DateTime: 2023/9/15 9:26
 **/
@Service
public class PublishServiceImpl extends ServiceImpl<PublishMapper, Publish> implements PublishService {

    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private MediaService mediaService;

    @Autowired
    private PublishService publishService;

    @Autowired
    private MessageClient messageClient;

    @Autowired
    private PublishRecodeService publishRecodeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String REDIS_ROUTINGKEY="inform.redis";

    private static final String ES_ROUTINGKEY="inform.es";

    /**
     * 查询预发布视频信息
     *
     * @return 返回预发布视频信息
     */
    @Override
    public R<List<Publish>> listPublish(Integer page,Integer pageSize,Publish publish) {
        Page<Publish>publishPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Publish>qw=new LambdaQueryWrapper<>();
        qw.eq(publish.getId()!=null,Publish::getId,publish.getId())
                .like(publish.getTitle()!=null && !publish.getTitle().equals(""),Publish::getTitle,publish.getTitle())
                .eq(publish.getCategory()!=null,Publish::getCategory,publish.getCategory())
                .like(publish.getUploaderName()!=null,Publish::getUploaderName,publish.getUploaderName());
        this.page(publishPage,qw);
        Map<String,Object>map=new HashMap<>();
        map.put("count",publishPage.getTotal());
        return R.success(publishPage.getRecords(),map);
    }





    /**
     * 审核通过
     *
     * @param publishId 预发布视频Id
     * @param auditorId 审核员Id
     * @return 结果信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> auditAccess(String publishId, Integer auditorId) {
        //1.根据Id从预发布表中查询预发布视频
        Publish byId = publishService.getById(publishId);
        //2.删除预发布视频，向视频表插入视频。（开启事务）
        publishService.removeById(publishId);
        Media media = new Media();
        BeanUtils.copyProperties(byId, media);
        media.setLikes(0);
        media.setComments(0);
        media.setViews(0);
        media.setStatus(1);
        mediaService.save(media);
        //3.修改发布记录，将状态修改为1，审核通过，更新修改时间
        boolean result = publishRecodeService.audit(publishId,1,null,auditorId);
        if (!result) {
            throw new RuntimeException("发布记录修改失败");
        }
        //4.向rabbitMq中添加信息,异步调用来存储缓存信息
        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_TOPICS_INFORM,REDIS_ROUTINGKEY, JSON.toJSONString(media));
        //5.向rabbitMq中添加信息,异步调用来存储es文档
        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_TOPICS_INFORM,ES_ROUTINGKEY,JSON.toJSONString(media));
        return R.success("审核完成");
    }



    /**
     * 审核未通过
     *
     * @param publishId 预发布视频Id
     * @param reason    未通过原因
     * @param auditorId 审核员Id
     * @return 结果信息
     */
    @Override
    @Transactional
    public R<String> auditFailed(String publishId, String reason, Integer auditorId) {
        //1.删除预发布表中的记录
        boolean deleteResult = publishService.removeById(publishId);
        if(!deleteResult){
            return R.error("未找到该发布记录");
        }
        //2.修改发布记录,将状态修改为审核未通过
        boolean result = publishRecodeService.audit(publishId, 2, reason, auditorId);
        if(!result){
            return R.error("审核出现异常");
        }
        return R.success("审核成功");
    }
}
